<?php

require_once 'q/dao.php';
require_once 'config/db.php';
require_once 'config/path.php';

class dao_admin_crawler extends q_dao {

    private $tables = array('7k7k', '4399');

    private $table;

    public function __construct($table){
        if(!in_array($table, $this->tables)){
            exit('bad table name');
        }

        $this->table = $table;
    }

    private static $_instance = array();
    public static function getInstance($table){
        if(!isset(self::$_instance[$table])){
            self::$_instance[$table] = new dao_admin_crawler($table);
        }
        return self::$_instance[$table];
    }

    public function get($id){
        $db = $this->_getdb(config_db::get('crawler'));
        $sql = "select * from flash_" . $this->table
            . " where id = '".$db->escape($id)."' "
            . " limit 1 ";

        return $db->query_assoc($sql);
    }

    public function get_list_total($search = array()){

        $db = $this->_getdb(config_db::get('crawler'));
        $sql = "select count(*) as total_num from flash_" . $this->table
            . " " ;

        return $db->query_one($sql);
    }


    public function get_list($offset, $limit, $search = array()){
        $offset = intval($offset);
        $limit  = intval($limit);

        $db = $this->_getdb(config_db::get('crawler'));
        $sql = "select * from flash_" . $this->table
            . " "
            . " order by id desc "
            . " limit " . $offset . ", " . $limit;

        $list = array();
        $res = $db->query($sql);
        while($row = $db->fetch($res)){
            $list[] = $row;
        }
        return $list;
    }

    public function set_refresh($id){
        $db = $this->_getdb(config_db::get('crawler'));

        $sql = "update flash_" . $this->table
            . " set refresh = '1' "
            . " where id = '".$db->escape($id)."' "
            . " limit 1 ";

        return $db->query($sql);

    }

    public static function get_image_file($table, $id){

        $padding = sprintf("%02d", $id);

        $file = config_path::$crawler_data
            . '/'
            . $table
            . '/'
            . substr($padding, -2)
            . '/'
            . $id 
            . '.jpg';

        return $file;
    }

    public static function get_flash_file($table, $id){

        $padding = sprintf("%02d", $id);

        $file = config_path::$crawler_data
            . '/'
            . $table
            . '/'
            . substr($padding, -2)
            . '/'
            . $id 
            . '.swf';

        return $file;
    }
}

